import { generateAccessible } from "@scpun/access";
import { arrayToTree, ComponentRecordType, GenerateMenuAndRoutesOptions, RouteRecordStringComponent } from "@scpun/core";
import { getUserRoutes } from "/@/api/oauth2";
import { BasicLayout, BlankLayout, IFrameLayout } from "/@/layout";

const forbiddenComponent = () => import("/@/views/_core/exception/403.vue");

async function generateAccess(options: GenerateMenuAndRoutesOptions) {
    const pageMap: ComponentRecordType = import.meta.glob("../../views/**/*.vue");

    const layoutMap: ComponentRecordType = {
        BASIC_LAYOUT: BasicLayout,
        BLANK_LAYOUT: BlankLayout,
        IFRAME_LAYOUT: IFrameLayout,
    };

    return await generateAccessible("backend", {
        ...options,
        fetchMenuListAsync: async () => {
            window.$message?.loading(`加载权限菜单...`, {
                duration: 1.5,
            });
            const appRoutes = await getUserRoutes();
            return arrayToTree<RouteRecordStringComponent>(appRoutes || []);
        },
        // 可以指定没有权限跳转403页面
        forbiddenComponent,
        // 如果 route.meta.menuVisibleWithForbidden = true
        layoutMap,
        pageMap,
    });
}

export { generateAccess };
